package com.back_end.NetWork.chart;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

//发送端，实现Runnable
public class TalkSend implements Runnable{

    DatagramSocket  socket  =   null;
    BufferedReader  reader  =   null;
    private int  fromPort;
    private String  toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);    //用于连接Socke，这是sender的port
            reader = new BufferedReader(new InputStreamReader(System.in)); //使用BufferedReader读取控制台输入的数据
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                String data = reader.readLine();  //此时为一行一行读的功能，将读到的字符串给data
                byte[] datas = data.getBytes();   //转为字节
                //数据放入容器，并指定对方的IP和端口
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                //发送
                socket.send(packet);
                if(data.equals("bye")){    //结束语句
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        socket.close();
    }
}
